<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分销套餐包列表</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css" media="all">
    <style>
        .productFxList-container {
            padding: 20px;
        }

        td[data-field="imgUrl"] div,
        td[data-field="negativeImgUrl"] div {
            height: 120px;
        }

        .lay-form {
            padding: 20px;
        }

        .productFxList-container {
            background-color: #fff;
        }

        .bar {
            display: flex;
            justify-content: flex-start;
            align-items: flex-end;
        }

        .searchInput {
            display: flex;
            align-items: flex-end;
        }

        .searchInput input {
            width: 200px;
        }

        
        .layui-form-label {
            padding: 0;
            padding-bottom: 4px;
            text-align: right;
            width: 120px;
        }

        .bar .layui-inline {
            margin-right: 20px;
        }

        .layui-table img {
            max-width: 200px;
            object-fit: contain;
        }

        .layui-table-cell {
            height: auto;
        }

        .fxProduct-container {
            padding: 20px;
        }

        .fxProduct-container {
            background-color: #fff;
        }
        .fxProduct-container form {
            width: 800px;
            margin: 0 auto;
            padding: 30px;
            border: 1px solid #eee;
        } 
        .layui-input-block {
            margin-left: 150px;
        }
        #fxProductList .layui-form-item{
            display: flex;
            justify-content: flex-start;
            align-items: center;
        }
        #fxProductList .layui-input-block {
            margin-left: 30px;
        }
        #fxProductList {
            padding-left: 30px;
        }
    </style>
</head>

<body>
    <div class="productFxList-container">

        <!-- 搜索 -->
        <!-- <div class="searchInput">
            <form class="layui-form" action="" lay-filter="resets">
                <div class="layui-inline">
                    <label class="layui-form-label">商品名称：</label>
                    <input class="layui-input" name="distributionName" placeholder="请输入客户昵称" autocomplete="off">
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">创建日期：</label>
                    <input type="text" class="layui-input" id="test1" name="createTime" placeholder="请输入申请时间"
                        autocomplete="off">
                </div>
                <button class="layui-btn" data-type="reload" lay-submit="" lay-filter="searchForm">搜索</button>
                <button class="layui-btn layui-btn-primary" data-type="reload" lay-submit=""
                    lay-filter="reset">重置</button>
            </form>
        </div> -->
        <button class="layui-btn" id="addPackage">添加分销套餐包</button>

        <table lay-filter="productFxListTable" class="layui-hide" id="productFxListTable"></table>
    </div>

</body>

<!-- 添加 -->
<script type="text/html" id="toolbarDemo">
    <div class="bar">
        <!-- <div class="layui-btn-container" style="margin-bottom:-5px;">
            <button class="layui-btn layui-btn-sm" lay-event="success">上架</button>
            <button class="layui-btn layui-btn-danger layui-btn-sm" lay-event="fail">下架</button>
        </div> -->

        <!-- 筛选 -->
        <!-- <div class="layui-form-item" id="status" style="margin-bottom:0">
            <label class="layui-form-label" style="width: 60px; text-align:right; margin-top:10px">状态：</label>
            <div class="layui-input-block" style="margin-left: 70px">
              <select name="stop" lay-filter="select">
                <option value="">全部</option>
                <option value="1">上架</option>
                <option value="0">下架</option>
              </select>
            </div>
        </div> -->
    </div>
</script>

<!-- 操作 -->
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
</script>

<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.5.7/layui.all.min.js"></script>
<script src="../utils.js"></script>
<script src="../addProduct/layedit.js"></script>
<script>
    layui.use(['table', 'upload', 'form', 'jquery', "laydate"], function () {
        var table = layui.table,
            upload = layui.upload,
            form = layui.form,
            laydate = layui.laydate,
            $ = layui.jquery,
            layedit = layui.layedit;
            var editContext = "";

        table.render({
            elem: '#productFxListTable'
            , toolbar: "#toolbarDemo"
            , url: window.baseUrl + '/distribution/getDistributionGoodsList'
            , method: 'post'
            , contentType: 'application/json'
            , headers: {
                Authorization: localStorage.token
            }
            , response: {
                statusCode: 200 //规定成功的状态码，默认：0
            }
            , cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 200,
                    "count": res.data.recordsTotal, //解析数据长度
                    "data": res.data.data //解析数据列表
                };
            }
            ,where:{
                goodsType: 1,
                length: 999999
            }
            , request: {
                pageName: 'start' //页码的参数名称，默认：page
                , limitName: 'length' //每页数据量的参数名，默认：limit
            }
            , cols: [[
                { type: 'checkbox' }
                , { field: 'distributionName', title: '分销套餐包名称'}
                , { field: 'price', title: '价格(元)' }
                // 这个status 状态时有时无啊，我擦
                // , {  title: '状态', templet: function(row) {
                //     return row.status == 1 ? "上架" : "下架"
                // } }
                , { title: '操作', toolbar: '#barDemo' }
            ]],
            page: true
        });

        laydate.render({
            elem: '#test1'
        });

        $("#addPackage").on("click", function() {
            showLayer();
        })

        function showLayer(data) {
            layer.open({
                type: 1,
                title: "添加/编辑分销套餐包",
                area: ['960px', '830px'], //宽高
                content: `
                    <div class="fxProduct-container">
                        <form class="layui-form" lay-filter="fxProduct">
                            <fieldset class="layui-elem-field layui-field-title">
                                <legend>分销套餐包基本信息</legend>
                            </fieldset>

                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>分销套餐包名称</label>
                                <div class="layui-input-block">
                                    <input type="text" name="distributionName" lay-verify="required" lay-reqtext="分销套餐包名称称是必填项，岂能为空？" placeholder="请输入分销套餐包名称"
                                        autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>套餐包价格</label>
                                <div class="layui-input-block">
                                    <input type="text" name="price" lay-verify="required|number" lay-reqtext="套餐包价格是必填项，岂能为空？" placeholder="请输入套餐包价格"
                                        autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <!-- <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>套餐包折扣</label>
                                <div class="layui-input-block">
                                    <input type="text" name="discount" lay-verify="required|number" lay-reqtext="套餐包折扣是必填项，岂能为空？" placeholder="请输入套餐包折扣"
                                        autocomplete="off" class="layui-input">
                                </div>
                            </div>
                             <div class="layui-form-item">
                                <label class="layui-form-label"><span style="color:red; font-size:16px;">* </span>套餐包购买限制</label>
                                <div class="layui-input-block">
                                    <input type="text" name="buyLimit" lay-verify="required|number" lay-reqtext="套餐包购买限制是必填项，岂能为空？" placeholder="请输入套餐包购买限制"
                                        autocomplete="off" class="layui-input">
                                </div>
                            </div> -->

                            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                                <legend>分销商品列表</legend>
                            </fieldset>

                            <div id="fxProductList"></div>


                            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                                <legend>套餐包简介</legend>
                            </fieldset>

                            <textarea id="fxProductDetails" data-type="des" style="display: none;"></textarea>

                            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                                <legend>销售属性</legend>
                            </fieldset>

                            <input type="hidden" name="id" id="fxId" />

                            <div class="layui-form-item">
                                <label class="layui-form-label">状态</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" checked="" name="status" lay-skin="switch" lay-filter="switchTest" lay-text="上架|稍后上架">
                                </div>
                            </div>
                    
                            
                            <div class="layui-form-item" style="text-align:center">
                                <div class="layui-input-block" style="margin-left: 0;">
                                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="addfxPackageProduct">立即提交</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                    </div>`,
                    success (layero, index){

                        ajax({
                            path: "/distribution/getDistributionGoodsList",
                            data: {
                                start: 1,
                                length: 9999999,
                                goodsType: 0
                            },
                            success: function (res) {
                                res.data.forEach(el => {
                                    delete el.des;
                                    $("#fxProductList").append(`
                                        <div class="layui-form-item check">
                                            <input type="checkbox" data-id="${el.id}" title="${el.distributionName}">
                                            
                                            <div class="layui-input-block">
                                                <input data-detail='${JSON.stringify(el)}' type="text" placeholder="请输入分销商品数量"
                                                    autocomplete="off" class="layui-input input${el.id}">
                                            </div>
                                        </div>
                                    `)
                                })

                                if (data && data.packageGoodList && data.packageGoodList.length) {
                                    data.packageGoodList.forEach(el => {
                                        $("input[data-id="+ el.goodId +"]").attr("checked", true);
                                        $(".input" + el.goodId).val(el.goodNum);
                                        $(".input" + el.goodId).attr("data-packageid", el.packageId);
                                        $(".input" + el.goodId).attr("data-currid", el.id);
                                    })
                                }
                                
                                form.render()
                            }
                        }, $)
                        
                        

                        // 富文本配置
                        editContext = layedit.build('fxProductDetails', {
                            uploadImage: {
                                url: window.baseUrl + '/file/uploadFile', 
                                type: 'post'
                            }
                        });
                        form.render();
                        setTimeout(function() {
                            layedit.setContent(editContext, data ? data.des : '');
                        }, 300)
                    }
            });
        }

        form.render();


        

        //工具栏事件
        // table.on('toolbar(productFxListTable)', function (obj) {
        //     var checkStatus = table.checkStatus(obj.config.id);
        //     switch (obj.event) {
        //         case 'success':
        //             //页面层
        //             var checkStatus = table.checkStatus('productFxListTable')
        //                 , data = checkStatus.data;
        //             if (!data.length) {
        //                 return layer.msg("请选择！")
        //             }
        //             data.forEach(el => {
        //                 el.status = 1;
        //                 ajax({
        //                     path: "/distribution/updateDistributionGoods",
        //                     data: el,
        //                     success: function (res) {
        //                         table.reload("productFxListTable");
        //                     }
        //                 }, $)
        //             })

        //             layer.msg("更新成功！")
        //             break;
        //         case 'fail':
        //             var checkStatus = table.checkStatus('productFxListTable')
        //                 , data = checkStatus.data;
        //             if (!data.length) {
        //                 return layer.msg("请选择！")
        //             }
        //             data.forEach(el => {
        //                 el.status = 0;
        //                 ajax({
        //                     path: "/distribution/updateDistributionGoods",
        //                     data: el,
        //                     success: function (res) {
        //                         table.reload("productFxListTable");
        //                     }
        //                 }, $)
        //             })

        //             layer.msg("更新成功！")
        //             break;
        //         case "add":
        //             showLayer();
        //             $('#fxId').val("");
        //             // window.location.href = "../addProduct/addfxPackageProduct.html";
        //             break;
        //     };
        // });

        // // 搜索
        // form.on("submit(searchForm)", function (e) {
        //     console.log(e);
        //     e.field.createTime = new Date(e.field.createTime).getTime();
        //     table.reload('productFxListTable', {
        //         page: {
        //             start: 1 //重新从第 1 页开始
        //         }
        //         , where: e.field
        //     });

        //     return false;
        // })


        // // 搜索
        // form.on("submit(reset)", function (e) {

        //     table.reload('productFxListTable', {
        //         page: {
        //             start: 1 //重新从第 1 页开始
        //         }
        //         , where: null
        //     });

        //     form.val("resets", {
        //         distributionName: "",
        //         createTime: ""
        //     });

        //     return false;
        // })


        // 筛选状态
        form.on("select(select)", function (e) {
            table.reload('productFxListTable', {
                page: {
                    start: 1 //重新从第 1 页开始
                }
                , where: {
                    status: e.value,
                    goodsType: 1
                }
            });

        })


        // 编辑和删除
        table.on("tool(productFxListTable)", function (data) {
            console.log(data.data);
            switch (data.event) {
                case "edit":
                    showLayer(data.data);
                    form.val('fxProduct', data.data);
                    break;
            }
        })

        // 提交
        form.on("submit(addfxPackageProduct)", function(obj) {
            console.log(editContext);
            obj.field.status = obj.field.status ? 1 : 0;
            obj.field.des = layedit.getContent(editContext)
            obj.field.goodsType = 1;
            obj.field.packageName = obj.field.distributionName

            
            if (!obj.field.id) {
                delete obj.field.id
            }
            delete obj.field.distributionName;

            console.log(obj.field);

            obj.field.distributionGoodList = [];
            
            $.each($('#fxProductList input[type="checkbox"]:checked'), function(i, item) {
                var doms = $(this).next().next().children().get(0);
                var jsons = JSON.parse($(doms).attr("data-detail"));

                var postData = {
                    goodNum: doms.value,
                    goodId: jsons.id
                }

                if ($(doms).attr("data-packageid") && $(doms).attr("data-currid")) {
                    postData.packageId = $(doms).attr("data-packageid");
                    postData.id = $(doms).attr("data-currid");
                }

                obj.field.distributionGoodList.push(postData)
            })
            
            ajax({
                path: "/distribution/saveOrUpdatePackage",
                data: obj.field,
                success: function (res) {
                    layer.closeAll();
                    layer.msg("操作成功!")
                    table.reload("productFxListTable");
                }
            }, $)

            return false;
        })
    });
</script>

</html>